package com.lagou.edu.server;

import java.io.*;

/**
 *  重定义classloader
 *  @author 胡益文
 * @since 2021/10/13 20:04
 */
public class WebappClassloader extends ClassLoader{

    private Context context;

    public WebappClassloader(ClassLoader parent, Context context) {
        super(parent);
        this.context = context;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String namePath = name.replace(".","/");
        //defineClass方法可以把二进制流字节组成的文件转换为一个java.lang.Class
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(context.getContextPath()+"/"+namePath+".class"));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int contentSize = 0;
            //获取输入字符大小
            while (contentSize == 0){
                contentSize = inputStream.available();
            }
            //缓存数组读写
            int byteSize = 1024 ; //定义1024缓存
            int readNum = 0; //读取字符数
            byte[] bytes = new byte[byteSize];
            while (readNum<contentSize){
                if(readNum+byteSize>contentSize){
                    bytes = new byte[contentSize-readNum];
                }
                inputStream.read(bytes);//读取
                bos.write(bytes);//输出
                bos.flush();
                readNum+=byteSize;
            }
            byte[] classBytes = bos.toByteArray();
            Class<?> c = this.defineClass(name, classBytes, 0, classBytes.length);
            return c;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }
}
